package my.mall.common.util

import java.time.Instant
import java.time.LocalDate
import java.time.LocalDateTime
import java.time.ZoneId
import java.time.format.DateTimeFormatter
import java.util.*
import java.util.concurrent.TimeUnit

object DateUtils {
    private val COMMON_FORMATTER: DateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")

    fun asDate(localDate: LocalDate): Date {
        return Date.from(localDate.atStartOfDay().atZone(ZoneId.systemDefault()).toInstant())
    }

    fun asDate(localDateTime: LocalDateTime): Date {
        return Date.from(localDateTime.atZone(ZoneId.systemDefault()).toInstant())
    }

    fun asLocalDate(date: Date): LocalDate {
        return Instant.ofEpochMilli(date.time).atZone(ZoneId.systemDefault()).toLocalDate()
    }

    fun asLocalDateTime(date: Date): LocalDateTime {
        return Instant.ofEpochMilli(date.time).atZone(ZoneId.systemDefault()).toLocalDateTime()
    }

    fun formatLocalDate(localDate: LocalDate?): String {
        return if (localDate == null) {
            ""
        } else localDate.format(DateTimeFormatter.ISO_LOCAL_DATE)
    }

    fun formatLocalDateTime(localDateTime: LocalDateTime?): String {
        return if (localDateTime == null) {
            ""
        } else localDateTime.format(COMMON_FORMATTER)
    }

    /**
     * 将毫秒数转换成秒数
     * @param millis 毫秒数
     * @return 秒数
     */
    fun convertMillisToSeconds(millis: Long): Long {
        return TimeUnit.SECONDS.convert(millis, TimeUnit.MILLISECONDS)
    }
}
